# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import codecs
from datetime import datetime,timedelta
import logging
from osapps.common.request import Command,Message
from osapps.gtest.model import *


class getpersonCommand(Command):
  def execute(self):
    #accept the name and url
    playerId = self.request.get("id")
    if not playerId:
      playerId = self.context["vid"]
      
    uid = ":".join([self.request.get("ctn"),playerId])
    player = DBLayer.getPlayer(uid)
    if(not player):
        player = Player(uid=uid,name=self.request.get("name"),photo=self.request.get("photo"))
        player.put()
        
    playerlogs = DBLayer.getProfile(uid)
    
    self.hasError(False)
    self.output(playerlogs)
    return self.NEXT
    
class answerCommand(Command):
  def execute(self):
    tagid = int(self.request.get("tagid") or '-1')
    uid = ":".join([self.context["ctn"],self.context["vid"]])
    
    answer = None
    try:
      answer = int(self.request.get("answer"))
    except Exception:
      pass

    tag = Tag.get_by_id(tagid)
    
    if not tag:
      self.output(Message('invalid_tag',None))
      return self.END
    
    
    if answer:
      logging.info("answer a question:" + str(answer))
      question = DBLayer.getNextQuestion(uid,tag)
      player = DBLayer.getPlayer(uid)
      
      if not question:
        self.output(Message('finish',None))
        return self.NEXT
        
      playlog = DBLayer.getPlaylog(uid,tag)
      if not playlog:
        logging.info("playlog is null,create playlog for " + uid)
        playlog = Playlog(tag=tag,uid=uid)
    
      if(checkAnswer(question,answer)):
        playlog.right = playlog.right + 1
        playlog.score = playlog.score + 3
        player.score = player.score + 3
      else:
        playlog.score = playlog.score + 1
        player.score = player.score + 1
        
      playlog.answered = playlog.answered + 1
      playlog.time = datetime.now()
      playlog.put()
      player.put()
    
    question = DBLayer.getNextQuestion(uid,tag)

    self.hasError(False)
    if not question:
      self.output(Message('finish',DBLayer.getPlaylog(uid,tag)))
    else:
      json = {"id":question.key().id(),"title":question.title,"seq":question.seq}
      json["answers"] = [{"id":a.key().id(),"text":a.text} for a in question.answers()]
      self.output(json)
    
    return self.NEXT
    
class tagsCommand(Command):
  def execute(self):
    uid = ":".join([self.context["ctn"],self.context["vid"]])
    tags = DBLayer.getAllTag()
    out = []
    for tag in tags:
      json = {"id":tag.key().id(),"name":tag.name,"qnumber":tag.qnumber}
      log = DBLayer.getPlaylog(uid,tag)
      if log:
        json.update({"answered":log.answered,"right":log.right,"score":log.score})
      else:
        json.update({"answered":0,"right":0,"score":0})
      out.append(json)
    self.hasError(False)
    self.output(out)
    return self.NEXT
    
class rankCommand(Command):
  def execute(self):
    ids = self.request.get("friendids")
    if(not ids):
      self.output(Message('nofriends',None))
      return self.END
    ctn = self.context['ctn']
    uid = ":".join([self.context['ctn'],self.context['vid']])
    friendids = ids.split(",")
    friendids = [":".join([ctn,id]) for id in friendids]
    friendids += [uid]
    
    
    ranks = DBLayer.getRank(friendids)
    self.hasError(False)
    
    index = 1
    for player in ranks:
        if(player.uid == uid):
            break
        index = index + 1
    logging.info("rank:" + str(index))
    
    
    ret = ranks[:3]
    ret.append({"rank":index})
    
    
    self.output(ret)
    return self.NEXT
        
    
        
def checkAnswer(question,answer):
  """check the answer,if right,return True"""
  for an in question.answers():
    if answer == an.key().id() and an.isRight:
      return True
      
  return False
    
